package com.sky.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    //修改部分，具体参考https://blog.csdn.net/RuanFun/article/details/135861498?spm=1001.2014.3001.5501
    private Orders orders;

    //用于百度地图的两个参数,shopAddress店铺地址，ak访问应用
    @Value("${sky.shop.address}")
    private String shopAddress;
    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //处理各种业务异常（地址簿为空、购物车为空）
            //处理地址簿为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //检查用户的收货地址是否超出配送范围
        checkOutOfRange(addressBook.getProvinceName()+addressBook.getCityName()+
                addressBook.getDistrictName()+addressBook.getDetail());
            //处理购物车为空
        ShoppingCart shoppingCart = new ShoppingCart();
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向orders订单表插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setAddress(addressBook.getDetail());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        //下一句为修改的部分
        this.orders = orders;
        orders.setUserId(userId);

        orderMapper.insert(orders);
        //向order_detail订单明细表插入n条数据
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }

        orderDetailMapper.insertBatch(orderDetails);
        //清空当前用户的购物车数据
        shoppingCartMapper.deleteByUserId(userId);
        //封装Vo返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     * @param userAddress
     */
    private void checkOutOfRange(String userAddress){
        //准备Map类型的发送信息
        Map<String, String> map = new HashMap<>();
        map.put("address", shopAddress);
        map.put("ak", ak);
        map.put("output", "json");
        //1. 获取店铺(出发地址)的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
        JSONObject jsonObject = JSONObject.parseObject(shopCoordinate);
        //如果本次API访问状态不为0即失败了，抛出异常
        if (!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException(MessageConstant.STORE_ADDRESS_PARSING_FAILED);
        }
        //准备好路径规划的店铺(出发地址)的经纬度坐标，origin 起点 double,double 纬度,经度
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");//纬度值
        String lng = location.getString("lng");//经度值
        String origin = lat + "," + lng;
        //2. 获取用户(收货地址)的经纬度坐标
        map.put("address", userAddress);
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
        jsonObject = JSONObject.parseObject(userCoordinate);
        //如果本次API访问状态不为0即失败了，抛出异常
        if (!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException(MessageConstant.RECEIVING_ADDRESS_PARSING_FAILED);
        }
        //准备好路径规划的用户(收货地址)的经纬度坐标，destination 终点 double,double 纬度,经度
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");//纬度值
        lng = location.getString("lng");//经度值
        String destination = lat + "," + lng;
        //3. 封装好所需信息，发送轻量级路线规划
        map.clear();
        map.put("ak", ak);
        map.put("origin", origin);
        map.put("destination", destination);
        map.put("riding_type", "1");//默认0, 0：普通自行车,1：电动自行车
        map.put("steps_info", "0");//是否下发step详情 1：下发step详情 0：不下发step详情
        //判断配送距离超过5000米部分
        String resultJson = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/riding", map);
        jsonObject = JSONObject.parseObject(resultJson);
        if (!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException(MessageConstant.DELIVERY_ROUTE_PLANNING_FAILED);
        }
        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");//在多条可行方案中取第一条方案
        if (distance > 5000){
            throw new OrderBusinessException(MessageConstant.OUT_OF_DELIVERY_RANGE);
        }
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

/*        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
*/
        //以下为修改的部分
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        Integer OrderPaidStatus = Orders.PAID;//支付状态，已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单
        LocalDateTime check_out_time = LocalDateTime.now();//更新支付时间
        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, this.orders.getId());

        Map map = new HashMap<>();
        map.put("type", 1);//消息类型,1表示来电提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + orders.getNumber());
        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 历史订单分页查询
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult historyOrdersPage(Integer page, Integer pageSize, Integer status) {
        //设置pagehelper参数
        PageHelper.startPage(page, pageSize);
        //进行查询
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setPage(page);
        ordersPageQueryDTO.setPageSize(pageSize);
        ordersPageQueryDTO.setStatus(status);

        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);
        ArrayList<OrderVO> orderVOS = getOrderVOS(ordersPage);
        //返回PageResult
        return new  PageResult(ordersPage.getTotal(), orderVOS);
    }

    private ArrayList<OrderVO> getOrderVOS(Page<Orders> ordersPage) {
        //判断是否有数据，如果有，则封装成OrderVO
        ArrayList<OrderVO> orderVOS = new ArrayList<>();
        if (ordersPage != null) {
            List<Orders> records = ordersPage.getResult();
            for (Orders record : records) {
                OrderDetail orderDetail = OrderDetail.builder()
                        .orderId(record.getId())
                        .build();
                List<OrderDetail> orderDetailList = orderDetailMapper.list(orderDetail);
                //封装OrderVO，将查询的数据放入
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(record, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                // 将订单菜品信息封装到orderVO
                orderVO.setOrderDishes(getOrderDishesStr(record));
                orderVOS.add(orderVO);
            }
        }
        return orderVOS;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    public OrderVO getOrderDetail(Long id) {
        //通过id进行查询Order
        Orders order = orderMapper.getById(id);
        //通过orderId进行查询OrderDetail
        OrderDetail orderDetail = OrderDetail.builder().orderId(id).build();
        List<OrderDetail> orderDetailList = orderDetailMapper.list(orderDetail);
        //封装OrderVo
        OrderVO orderVO = OrderVO.builder()
                .orderDetailList(orderDetailList)
                .build();
        BeanUtils.copyProperties(order, orderVO);
        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    public void cancelOrder(Long id) throws Exception{
        //校验订单是否存在
        Orders orderById = orderMapper.getById(id);
        if (orderById == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        //订单3已接单、4派送中，用户取消订单需电话沟通商家
        Integer orderStatus = orderById.getStatus();
        if (orderStatus >= 3 && orderStatus <= 4) {
            throw new OrderBusinessException(MessageConstant.CANCEL_ORDER_NEED_CALL_MERCHANT);
        }
        //如果在待接单状态下取消订单，需要给用户退款
        Orders order = new Orders();
        order.setId(id);
        if (orderStatus.equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            weChatPayUtil.refund(orderById.getNumber(),
                    orderById.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            //支付状态修改为 退款
            order.setPayStatus(Orders.REFUND);
        }
        //取消订单后需要将订单状态修改为“已取消”
        order.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    /**
     * 再来一单,先清空购物车否则购物车里有一样的商品会出bug
     * @param id
     */
    public void repetition(Long id) {
        //根据id查询OrderDetail得到商品信息
        List<OrderDetail> orderDetailList = orderDetailMapper.list(OrderDetail.builder().orderId(id).build());
        //封装好购物车信息
        Long userId = BaseContext.getCurrentId();
        ArrayList<ShoppingCart> shoppingCartList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            //填写属性值
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartList.add(shoppingCart);
        }
        //清空购物车
        shoppingCartMapper.deleteByUserId(userId);
        //执行插入购物车信息
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //设置pageHelper参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //进行查询
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);
        //判断是否有数据，如果有，则封装成OrderVO
        ArrayList<OrderVO> orderVOS = getOrderVOS(ordersPage);
        //返回PageResult
        return new  PageResult(ordersPage.getTotal(), orderVOS);
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    public String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        OrderDetail orderDetail = OrderDetail.builder().orderId(orders.getId()).build();
        List<OrderDetail> orderDetailList = orderDetailMapper.list(orderDetail);
        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());
        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 各个状态的订单数量统计
     */
    public OrderStatisticsVO statistics() {
        //根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countByStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countByStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS);
        //封装数据到 OrderStatisticsVO ,返回数据
        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                .toBeConfirmed(toBeConfirmed)
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .build();
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        //查询订单
        Long orderId = ordersRejectionDTO.getId();
        Orders order = orderMapper.getById(orderId);
        //只有订单处于“待接单”状态时可以执行拒单操作，其他状态抛出异常
        if (order == null || !order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //商家拒单时，如果用户已经完成了支付，需要为用户退款
        Integer orderPayStatus = order.getPayStatus();
        if (orderPayStatus.equals(Orders.PAID)) {
            String refund = weChatPayUtil.refund(order.getNumber(),
                    order.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }
        // 根据订单id更新订单状态、拒单原因、取消时间
        Orders order1 = new Orders();
        order1.setId(orderId);
        order1.setStatus(Orders.CANCELLED);
        order1.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        order1.setCancelTime(LocalDateTime.now());

        orderMapper.update(order1);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        //查询订单
        Long orderId = ordersCancelDTO.getId();
        Orders order = orderMapper.getById(orderId);
        //检查状态，状态为已取消、待接单抛出异常
        if (order == null || order.getStatus().equals(Orders.TO_BE_CONFIRMED) || order.getStatus().equals(Orders.CANCELLED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //商家取消订单时，如果用户已经完成了支付，需要为用户退款
        Integer orderPayStatus = order.getPayStatus();
        if (orderPayStatus.equals(Orders.PAID)) {
            String refund = weChatPayUtil.refund(order.getNumber(),
                    order.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }
        // 根据订单id更新订单状态、取消原因、取消时间
        Orders order1 = new Orders();
        order1.setId(orderId);
        order1.setStatus(Orders.CANCELLED);
        order1.setCancelReason(ordersCancelDTO.getCancelReason());
        order1.setCancelTime(LocalDateTime.now());

        orderMapper.update(order1);
    }

    /**
     * 派送订单
     * @param id
     */
    public void delivery(Long id) {
        //查询订单
        Orders order = orderMapper.getById(id);
        //只有状态为“待派送”的订单可以执行派送订单操作，其他的抛出异常
        if (order == null || !order.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //派送订单其实就是将订单状态修改为“派送中”
        Orders orders1 = Orders.builder()
                .id(order.getId())
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders1);
    }

    /**
     * 完成订单
     * @param id
     */
    public void complete(Long id) {
        //查询订单
        Orders order = orderMapper.getById(id);
        //只有状态为“派送中”的订单可以执行订单完成操作，其他的抛出异常
        if (order == null || !order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //派送订单其实就是将订单状态修改为“派送中”
        Orders orders1 = Orders.builder()
                .id(order.getId())
                .status(Orders.COMPLETED)
                .build();
        orderMapper.update(orders1);
    }

    /**
     * 用户催单
     * @param id
     */
    public void reminder(long id) {
        // 查询订单是否存在
        Orders order = orderMapper.getById(id);
        if (order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//消息类型,2表示用户催单
        map.put("orderId", order.getId());
        map.put("content", "订单号：" + order.getNumber());
        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }
}
